package com.suning.park.admin.util.epps;

import com.suning.park.admin.exception.BusinessFailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/12.
 */
public class SignatureUtil {

    private static final Logger logger = LoggerFactory.getLogger(SignatureUtil.class);

    public static String digest(Map<String, String> map)
            throws BusinessFailException {
        if ((map == null) || (map.size() == 0))
            throw new BusinessFailException("加密内容不能为空");

        try {
            return Digest.digest(map, null);
        } catch (Exception e) {
            logger.error("MD5摘要异常", e);
            throw new BusinessFailException("MD5加密错误");
        }
    }

    public static String digest(Map<String, String> map, List<String> excudeKeylist)
            throws BusinessFailException {
        if ((map == null) || (map.size() == 0))
            throw new BusinessFailException("加密内容不能为空");

        try {
            return Digest.digest(map, excudeKeylist);
        } catch (Exception e) {
            logger.error("业务字段MD5摘要异常", e);
            throw new BusinessFailException("MD5加密错误");
        }
    }

    public static String sign(String data, String privateKeyStr)
            throws BusinessFailException {
        if ((data == null) || (data.length() == 0))
            throw new BusinessFailException("待加签参数为空");

        if ((privateKeyStr == null) || (privateKeyStr.length() == 0))
            throw new BusinessFailException("私钥字符串为空");

        try {
            PrivateKey privateKey = RSAUtil.getPrivateKey(privateKeyStr);

            return RSAUtil.sign(data, privateKey);
        } catch (Exception e) {
            logger.error("签名异常", e);
            throw new BusinessFailException("签名异常");
        }
    }

    public static boolean verifySignature(String signData, String signature, String publicKey)
            throws BusinessFailException {
        if ((signData == null) || (signData.length() == 0))
            throw new BusinessFailException("原数据字符串为空");

        if ((signature == null) || (signature.length() == 0))
            throw new BusinessFailException("签名字符串为空");

        if ((publicKey == null) || (publicKey.length() == 0))
            throw new BusinessFailException("公钥字符串为空");

        try {
            PublicKey pubKey = RSAUtil.getPublicKey(publicKey);

            return RSAUtil.vertiy(signData, signature, pubKey);
        } catch (Exception e) {
            logger.error("验证签名异常", e);
            throw new BusinessFailException("验证签名异常");
        }
    }
}
